<template>
  <div class="app-container">
    <div class="table">
      <el-form class="search-container" :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="学生姓名" prop="nickName">
          <el-input v-model="queryParams.nickName" placeholder="请输入学生姓名" clearable style="width: 200px" @keyup.enter="handleQuery" />
        </el-form-item>

        <el-form-item label="学号" prop="stuId">
          <el-input v-model="queryParams.stuId" placeholder="请输入学号" clearable style="width: 200px" @keyup.enter="handleQuery" />
        </el-form-item>

        <el-form-item label="学院" prop="deptId">
          <el-select v-model="queryParams.deptId" placeholder="请选择学院" clearable filterable style="width: 200px" @change="onDeptFilterChange">
            <el-option v-for="opt in deptOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="年级" prop="gradeId">
          <el-select v-model="queryParams.gradeId" placeholder="请选择年级" clearable filterable style="width: 200px" :disabled="!queryParams.deptId" @change="onGradeFilterChange">
            <el-option v-for="opt in gradeOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="专业" prop="majorId">
          <el-select v-model="queryParams.majorId" placeholder="请选择专业" clearable filterable style="width: 200px" :disabled="!queryParams.gradeId">
            <el-option v-for="opt in majorOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="table-container">
        <el-row :gutter="10" class="mb8">
          <span>学生信息列表</span>
          <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="getList"
            add="system:student:add"
            @handleAdd="handleAdd"
            update="system:student:edit"
            @handleUpdate="handleUpdate"
            del="system:student:remove"
            @handleDelete="handleDelete"
            imp="system:student:import"
            @handleImport="handleImport"
            exp="system:student:export"
            @handleExport="handleExport"
            :single="single"
            :multiple="multiple"
          ></right-toolbar>
        </el-row>
        <el-table v-loading="loading" class="table-content" border :data="studentList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="学号" align="center" prop="stuId" />
          <el-table-column label="学生姓名" align="center" prop="user.nickName" />
          <el-table-column label="所属学院" align="center" prop="user.dept.deptName" />
          <el-table-column label="年级" align="center" prop="grade.gradeName" />
          <el-table-column label="专业" align="center" prop="major.majorName" />
          <el-table-column label="邮箱" align="center" prop="user.email" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template v-slot="{ row }">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(row)" v-hasPermi="['system:student:edit']">修改</el-button>
              <el-button link type="danger" icon="Delete" @click="handleDelete(row)" v-hasPermi="['system:student:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination class="pagination-container" v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
      </div>
    </div>
  </div>
  <index-dialog ref="dialogRef" :tree="gradeTreeData"  @update="updateHandler"></index-dialog>
  <!-- 学生数据导入对话框 -->
  <excel-upload-dialog
    ref="uploadDialogRef"
    title="学生数据导入"
    :upload-url="uploadUrl"
    template-url="system/student/exportTemplate"
    @success="handleUploadSuccess"
  />
</template>

<script setup name="Student">
import { listStudent, getStudent, delStudent, addStudent, updateStudent } from '@/api/student'
import { getGradeTree } from '@/api/grade'
import { getCurrentInstance, ref } from 'vue'
import indexDialog from './components/indexDialog.vue'
import ExcelUploadDialog from '@/components/business/ExcelUploadDialog.vue'
const { proxy } = getCurrentInstance()

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  nickName: '',
  deptId: '',
  gradeId: '',
  majorId: ''
})
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const studentList = ref([])
const dialogRef = ref(null)
const uploadDialogRef = ref(null)
const queryRef = ref(null)

// 上传地址
const uploadUrl = ref(import.meta.env.VITE_APP_BASE_API + '/system/student/importData')

const queryHandler = () => {
  queryParams.value.pageNum = 1
  getList()
}

// 下拉选项：学院、年级、专业
const deptOptions = ref([])
const gradeOptions = ref([])
const majorOptions = ref([])
const gradeTreeData = ref([])

async function loadGradeAndMajors() {
  try {
    const res = await getGradeTree()
    const list = Array.isArray(res.data) ? res.data : []
    gradeTreeData.value = list
    // 学院下拉
    deptOptions.value = list.map((dept) => ({ value: dept.deptId, label: dept.deptName }))
    // 初始化年级下拉（根据是否选择了学院动态处理）
    updateGradeOptionsForDept()
    updateMajorOptions()
  } catch (e) {
    deptOptions.value = []
    gradeOptions.value = []
    majorOptions.value = []
  }
}

function onDeptFilterChange() {
  // 切换学院时清空年级与专业，并刷新年级选项
  queryParams.value.gradeId = ''
  queryParams.value.majorId = ''
  updateGradeOptionsForDept()
  updateMajorOptions()
}

function updateGradeOptionsForDept() {
  const did = queryParams.value.deptId
  const list = gradeTreeData.value
  if (!did) {
    // 未选择学院时，扁平化所有年级
    gradeOptions.value = list.flatMap((dept) => (dept.children || []).map((g) => ({ value: g.gradeId, label: g.gradeName })))
    return
  }
  const deptNode = list.find((d) => d.deptId === did)
  gradeOptions.value = (deptNode?.children || []).map((g) => ({ value: g.gradeId, label: g.gradeName }))
}

function onGradeFilterChange() {
  // 选择年级时清空专业并刷新专业选项
  queryParams.value.majorId = ''
  updateMajorOptions()
}

function updateMajorOptions() {
  const gid = queryParams.value.gradeId
  if (!gid) {
    majorOptions.value = []
    return
  }
  // 在树中查找选中的年级下的专业
  for (const dep of gradeTreeData.value) {
    const gradeNode = (dep.children || []).find((g) => g.gradeId === gid)
    if (gradeNode) {
      majorOptions.value = (gradeNode.children || []).map((m) => ({ value: m.majorId, label: m.majorName }))
      return
    }
  }
  majorOptions.value = []
}

const getList = () => {
  loading.value = true
  listStudent(queryParams.value).then(({ data }) => {
    studentList.value = data.rows
    console.log(studentList.value)
    total.value = data.total
    loading.value = false
  })
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}
// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.studentId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}
/** 重置按钮操作 */
const resetQuery = () => {
  proxy.resetForm('queryRef')
  // 清空联动状态并重新加载选项
  queryParams.value.deptId = ''
  queryParams.value.gradeId = ''
  queryParams.value.majorId = ''
  deptOptions.value = []
  gradeOptions.value = []
  majorOptions.value = []
  loadGradeAndMajors()
  queryHandler()
}
/** 修改按钮操作 */
const handleUpdate = (row) => {
  const studentId = row?.studentId || ids.value
  dialogRef.value.openDialog(studentId)
}
/** 新增按钮操作 */
const handleAdd = () => {
  dialogRef.value.openDialog()
}
/** 删除按钮操作 */
const handleDelete = (row) => {
  const studentId = row?.studentId || ids.value
  proxy.$modal
    .confirm('是否确认删除编号为"' + studentId + '"的数据项?')
    .then(function () {
      return delStudent(studentId)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}
const updateHandler = () => {
  queryHandler()
}

/** 导入按钮操作 */
const handleImport = () => {
  uploadDialogRef.value.open()
}

/** 导入成功回调 */
const handleUploadSuccess = () => {
  getList()
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy.download('system/student/export', { ...queryParams.value }, `student_${new Date().getTime()}.xlsx`)
}

loadGradeAndMajors()
getList()
</script>
